package com.legendframework.core.cmd.ioc;

import com.legendframework.core.Store;
import com.legendframework.core.aop.AbstractProxy;
import com.legendframework.core.cmd.annotation.Command;
import com.legendframework.core.ioc.CommonBeansGenerate;
import com.legendframework.core.ioc.exception.BeansException;
import com.legendframework.core.cmd.BaseCommand;
import com.legendframework.core.cmd.ICommand;
import com.legendframework.core.AbstractLegendPlugin;
import com.legendframework.core.dao.Return;
import com.legendframework.core.support.lang3.StringUtils;

import java.lang.annotation.Annotation;

/**
 * @see Command 方式的Bean注入类型
 */
public class CommandBeansGenerate extends CommonBeansGenerate {

    public CommandBeansGenerate(Store store) {
        super(store);
    }

    @Override
    public String getBeanName(Class<?> cls) {
        return StringUtils.isEmpty(cls.getAnnotation(Command.class).value()) ? cls.getName() : cls.getAnnotation(Command.class).value();
    }

    @Override
    public Class<? extends Annotation> getAnnotation() {
        return Command.class;
    }

    @Override
    public void successHandle(String beanName, Object bean , AbstractLegendPlugin plugin) {
        ((BaseCommand) bean).setPlugin(plugin);
        plugin.getStore().getCommandManagerStore().registerCommond(plugin,(ICommand) bean);
    }

    @Override
    protected Return<String, Object> newInstance(Class<?> cls, AbstractLegendPlugin plugin) {
        if (!BaseCommand.class.isAssignableFrom(cls)) {
            throw new BeansException("这个类: '"+cls.getName()+"'需要是: '"+BaseCommand.class.getName()+"' 的子类");
        }
        return super.newInstance(cls, plugin);
    }

    @Override
    protected AbstractProxy getProxyAop() {
        return store.getTransactionProxy().addTransaction(store.getYamlTransaction()).addTransaction(store.getJdbcTransaction());
    }
}
